package com.cc.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cc.blog.entity.Category;
import com.cc.blog.mapper.CategoryMapper;
import com.cc.blog.service.CategoryService;
import com.cc.blog.vo.CategoryVo;
import com.cc.blog.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public CategoryVo findCategoryById(Long id) {
        CategoryVo categoryVo = new CategoryVo();
        Category category = categoryMapper.selectById(id);
        if (category != null) {
            BeanUtils.copyProperties(category,categoryVo);
        }
        return categoryVo;
    }

    @Override
    public Result findAllCategory() {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //减少查询时间，增加条件
        queryWrapper.select(Category::getId,Category::getCategoryName);
        List<Category> categoryList = categoryMapper.selectList(queryWrapper);
        return Result.success(copyList(categoryList));
    }

    @Override
    public Result findAllCategoryDetail() {
        List<Category> categoryList = categoryMapper.selectList(new LambdaQueryWrapper<>());
        return Result.success(copyList(categoryList));
    }

    @Override
    public Result findAllCategoryDetailById(Long id) {
        Category category = categoryMapper.selectById(id);
        CategoryVo categoryVo = copy(category);
        return Result.success(categoryVo);
    }

    private List<CategoryVo> copyList(List<Category> categoryList) {
        List<CategoryVo> list = new ArrayList<>();
        for (Category c : categoryList) {
            list.add(copy(c));
        }
        return list;
    }

    private CategoryVo copy(Category c) {
        CategoryVo categoryVo = new CategoryVo();
        categoryVo.setId(String.valueOf(c.getId()));
        BeanUtils.copyProperties(c,categoryVo);
        return categoryVo;
    }
}
